package com.thread;

/**
 * Created by john on 2016/4/11.
 */
public class SynchronizedThreadTest3 extends Thread{

    private  MyTest myTest;

    public SynchronizedThreadTest3( MyTest myTest){
        this.myTest = myTest;
    }
    @Override
    public void run() {
        myTest.setNum("a");
    }

    public static void main(String[] args) {
       /*多线程单一资源，顺序执行。多对象单锁
       synchronized 取得的锁都是对象锁，而不是把一段代码或者方法当作锁，所以那个线程先执行带synchronized
       关键字的方法，哪个线程就持有该方法所属对象的锁Lock，那么其他线程只能呈现等待状态，前提是多个线程访问的是同一个对象。
        other set over
        b:num = 100
        a set over
        a:num = 200*/
        MyTest m = new MyTest();
        SynchronizedThreadTest3    t3 = new SynchronizedThreadTest3(m);  // b
        SynchronizedThreadTest4    t4 = new SynchronizedThreadTest4(m);  // a
        t4.start();
        t3.start();

        /**
         * 多对象多锁
         * 多个线程方位多个对象，则会创建多个锁。所以各自互不影响。不用等待其他线程释放锁。
         * other set over
             a set over
             a:num = 200
             b:num = 100
         */
      /*  MyTest m = new MyTest();
        MyTest m1 = new MyTest();
        SynchronizedThreadTest3    t3 = new SynchronizedThreadTest3(m);
        SynchronizedThreadTest4    t4 = new SynchronizedThreadTest4(m1);
        t4.start();
        t3.start();*/
    }
}

class SynchronizedThreadTest4 extends  Thread{
    private  MyTest myTest;

    public SynchronizedThreadTest4( MyTest myTest){
        this.myTest = myTest;
    }
    @Override
    public void run() {
        myTest.setNum("b");
    }
}

class MyTest{

    private int num = 0;

    public synchronized void setNum(String str){

        if("a".equals(str)){
            num = 200;
            System.out.println("a set over");
        }else {
            num = 100;
            System.out.println("other set over");
        }
        System.out.println(str+":num = "+num);
    }

}